<template>
  <view class="fee-detail-page">
    <!-- 费用状态卡片 -->
    <view class="status-section" v-if="feeInfo">
      <view class="status-card">
        <view class="status-header">
          <text class="status-title">{{ feeInfo.feeTypeName || '物业费' }}</text>
          <view class="status-tag">
            <u-tag 
              :text="getStatusText(feeInfo.paymentStatus)" 
              :type="getStatusType(feeInfo.paymentStatus)" 
              size="mini"
            />
          </view>
        </view>
        <view class="status-desc">{{ getStatusDescription(feeInfo.paymentStatus) }}</view>
      </view>
    </view>

    <!-- 基本信息 -->
    <view class="info-section" v-if="feeInfo">
      <view class="info-card">
        <view class="card-title">基本信息</view>
        <view class="info-list">
          <view class="info-item">
            <view class="info-label">
              <u-icon name="home" size="16" color="#666"></u-icon>
              <text>房屋地址</text>
            </view>
            <text class="info-value">{{ feeInfo.householdAddress || '--' }}</text>
          </view>
          <view class="info-item">
            <view class="info-label">
              <u-icon name="calendar" size="16" color="#666"></u-icon>
              <text>计费周期</text>
            </view>
            <text class="info-value">{{ feeInfo.billingPeriod || '--' }}</text>
          </view>
          <view class="info-item">
            <view class="info-label">
              <u-icon name="clock" size="16" color="#666"></u-icon>
              <text>到期日期</text>
            </view>
            <text class="info-value due-date">{{ feeInfo.dueDate || '--' }}</text>
          </view>
          <view class="info-item">
            <view class="info-label">
              <u-icon name="rmb-circle" size="16" color="#666"></u-icon>
              <text>费用金额</text>
            </view>
            <text class="info-value amount">¥{{ formatAmount(feeInfo.amount) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="detail-section" v-if="feeInfo">
      <view class="detail-card">
        <view class="card-title">费用明细</view>
        <view class="detail-list">
          <view class="detail-item">
            <text class="detail-label">应收金额</text>
            <text class="detail-value">¥{{ formatAmount(feeInfo.amount) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">已缴金额</text>
            <text class="detail-value">¥{{ formatAmount(feeInfo.paidAmount) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">剩余金额</text>
            <text class="detail-value unpaid">¥{{ formatAmount(feeInfo.unpaidAmount || feeInfo.amount) }}</text>
          </view>
          <view class="detail-item" v-if="getSafeAmount(feeInfo.lateFee) > 0">
            <text class="detail-label">滞纳金</text>
            <text class="detail-value late-fee">¥{{ formatAmount(feeInfo.lateFee) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 缴费进度 -->
    <view class="progress-section" v-if="feeInfo">
      <view class="progress-card">
        <view class="card-title">缴费进度</view>
        <view class="progress-content">
          <view class="progress-info">
            <text class="progress-text">已缴费</text>
            <text class="progress-amount">¥{{ formatAmount(feeInfo.paidAmount) }}</text>
          </view>
          <view class="progress-bar">
            <view 
              class="progress-fill" 
              :style="{ width: getProgressPercentage() + '%' }"
            ></view>
          </view>
          <view class="progress-percentage">{{ getProgressPercentage() }}%</view>
        </view>
      </view>
    </view>

    <!-- 缴费记录 -->
    <view class="records-section" v-if="paymentRecords.length > 0">
      <view class="records-card">
        <view class="card-title">缴费记录</view>
        <view class="records-list">
          <view 
            v-for="(record, index) in paymentRecords" 
            :key="index"
            class="record-item"
          >
            <view class="record-info">
              <text class="record-time">{{ record.paymentTime }}</text>
              <text class="record-method">{{ record.paymentMethod }}</text>
            </view>
            <text class="record-amount">¥{{ record.amount }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 扫码支付区域 - 根据缴费状态显示 -->
    <view class="payment-section" v-if="feeInfo && canShowPayment">
      <view class="payment-card">
        <view class="card-title">
          <u-icon name="qr-code" color="#007aff" size="20"></u-icon>
          <text>扫码支付</text>
        </view>
        
        <!-- 物业公司信息 -->
        <view class="company-info" v-if="paymentInfo">
          <view class="company-name">{{ paymentInfo.companyName }}</view>
          <view class="company-desc" v-if="paymentInfo.paymentDescription">
            {{ paymentInfo.paymentDescription }}
          </view>
        </view>
        
        <!-- 收款二维码 -->
        <view class="qr-code-container" v-if="hasPaymentQrCodeFiles">
          <view class="qr-code-title">请扫描下方二维码进行支付</view>
          <view class="qr-code-images">
            <AppImagePreview 
              :images="paymentQrCodeFiles"
              :show-image-info="false"
              empty-text="暂无收款码"
              @preview="handleImagePreview"
              @error="handleImageError"
              @load="handleImageLoad"
            />
          </view>
          <view class="qr-code-tip">点击二维码可放大查看</view>
        </view>
        
        <!-- 支付账户信息 -->
        <view class="payment-account-info" v-if="paymentInfo && paymentInfo.paymentAccount">
          <view class="account-title">银行转账信息</view>
          <view class="account-item">
            <text class="account-label">收款账户：</text>
            <text class="account-value">{{ paymentInfo.paymentAccount }}</text>
          </view>
          <view class="account-item" v-if="paymentInfo.paymentBank">
            <text class="account-label">开户银行：</text>
            <text class="account-value">{{ paymentInfo.paymentBank }}</text>
          </view>
        </view>
        
        <!-- 联系信息 -->
        <view class="contact-info" v-if="paymentInfo && (paymentInfo.contactPhone || paymentInfo.serviceHotline)">
          <view class="contact-title">联系信息</view>
          <view class="contact-item" v-if="paymentInfo.contactPhone">
            <text class="contact-label">联系电话：</text>
            <text class="contact-value" @click="handleCall(paymentInfo.contactPhone)">
              {{ paymentInfo.contactPhone }}
            </text>
          </view>
          <view class="contact-item" v-if="paymentInfo.serviceHotline">
            <text class="contact-label">服务热线：</text>
            <text class="contact-value" @click="handleCall(paymentInfo.serviceHotline)">
              {{ paymentInfo.serviceHotline }}
            </text>
          </view>
        </view>
        
        <!-- 支付说明 -->
        <view class="payment-instructions">
          <view class="instructions-title">支付说明</view>
          <view class="instructions-content">
            <text class="instruction-item">1. 使用微信或支付宝扫描上方二维码</text>
            <text class="instruction-item">2. 输入缴费金额：¥{{ getPaymentAmount() }}</text>
            <text class="instruction-item">3. 备注房号：{{ feeInfo.householdAddress || '--' }}</text>
            <text class="instruction-item">4. 完成支付后截图保存</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section" v-if="feeInfo">
      <view class="action-buttons">
        <u-button 
          v-if="feeInfo.paymentStatus !== 'PAID' && feeInfo.paymentStatus !== 1"
          type="warning" 
          size="large"
          @click="handleReminder"
        >
          申请延期
        </u-button>
        <u-button 
          type="info" 
          size="large"
          @click="handleContact"
        >
          联系客服
        </u-button>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-section">
      <u-loading-icon mode="spinner" size="24"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-if="errorMessage" class="error-section">
      <u-empty 
        mode="error" 
        :text="errorMessage"
        :icon="'error-circle'"
      >
        <u-button 
          type="primary" 
          size="small"
          @click="retryLoad"
        >
          重试
        </u-button>
      </u-empty>
    </view>
  </view>
</template>

<script setup>
/**
 * 物业费详情页面 - 集成缴费功能版本
 * @author Wu.Liang
 * @date 2025-01-30
 * @description 显示物业费详细信息，集成在线缴费功能，避免页面跳转
 * @version 2.0 - 页面合并优化版本
 */

import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { propertyFeeApi, propertyPaymentApi } from '@/api/property'
import AppImagePreview from '@/components/AppImagePreview.vue'

// 响应式数据
  const feeInfo = ref(null)
  const paymentRecords = ref([])
  const paymentInfo = ref(null)
  const loading = ref(false)
  const errorMessage = ref('')
  const feeId = ref('')
  const householdId = ref('')

// 计算属性：处理收款码数据
const hasPaymentQrCodeFiles = computed(() => {
  if (!paymentInfo.value || !paymentInfo.value.paymentQrCode) {
    return false
  }
  try {
    const qrCodeFiles = JSON.parse(paymentInfo.value.paymentQrCode)
    return Array.isArray(qrCodeFiles) && qrCodeFiles.length > 0
  } catch (error) {
    console.error('解析收款码数据失败:', error)
    return false
  }
})

const paymentQrCodeFiles = computed(() => {
  if (!paymentInfo.value || !paymentInfo.value.paymentQrCode) {
    return []
  }
  try {
    const qrCodeFiles = JSON.parse(paymentInfo.value.paymentQrCode)
    return Array.isArray(qrCodeFiles) ? qrCodeFiles : []
  } catch (error) {
    console.error('解析收款码数据失败:', error)
    return []
  }
})

// 计算属性
const canShowPayment = computed(() => {
  if (!feeInfo.value) return false
  const status = feeInfo.value.paymentStatus
  return status === 'UNPAID' || status === 'PARTIAL' || status === 0 || status === 2
})

// 页面生命周期
onLoad((options) => {
  if (options.id) {
    feeId.value = options.id
    loadFeeDetail(options.id)
  } else {
    errorMessage.value = '参数错误：缺少费用ID'
  }
})

// 方法
const handleBack = () => {
  uni.navigateBack()
}

// 加载费用详情
const loadFeeDetail = async (id) => {
  loading.value = true
  errorMessage.value = ''
  
  try {
    const response = await propertyFeeApi.getFeeDetail(id)
          if (response.code === 200) {
        feeInfo.value = response.data
        // 如果费用详情中包含房户ID，则加载收款码信息
        if (response.data.householdId && !householdId.value) {
          householdId.value = response.data.householdId
          await loadPaymentInfo(response.data.householdId)
        }
        // 加载缴费记录
        await loadPaymentRecords(id)
      } else {
      throw new Error(response.message || '获取费用详情失败')
    }
  } catch (error) {
    console.error('获取费用详情失败:', error)
    errorMessage.value = error.message || '获取费用详情失败'
    uni.showToast({
      title: '获取费用详情失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载缴费记录
const loadPaymentRecords = async (feeId) => {
  try {
    const response = await propertyFeeApi.getPaymentRecords(feeId)
    if (response.code === 200) {
      paymentRecords.value = response.data || []
    }
  } catch (error) {
    console.error('获取缴费记录失败:', error)
    // 缴费记录获取失败不影响主页面显示
  }
}

// 重试加载
const retryLoad = () => {
  if (feeId.value) {
    loadFeeDetail(feeId.value)
  }
}

// 加载收款码信息
const loadPaymentInfo = async (householdId) => {
  if (!householdId) {
    console.warn('房户信息不完整，无法获取收款码')
    return
  }
  
  try {
    const response = await propertyPaymentApi.getPaymentInfoByHouseholdId(householdId)
    if (response.code === 200) {
      paymentInfo.value = response.data
      console.log('获取收款码信息成功:', response.data)
    } else {
      console.warn('获取收款码信息失败:', response.message)
    }
  } catch (error) {
    console.error('获取收款码信息失败:', error)
    // 收款码获取失败不影响主页面显示
  }
}

// 获取缴费金额
const getPaymentAmount = () => {
  if (!feeInfo.value) return '0.00'
  
  // 确保数据类型安全，转换为数字类型
  const unpaidAmount = Number(feeInfo.value.unpaidAmount) || Number(feeInfo.value.amount) || 0
  const lateFee = Number(feeInfo.value.lateFee) || 0
  
  // 验证数字的有效性
  if (isNaN(unpaidAmount) || isNaN(lateFee)) {
    console.warn('费用金额数据异常:', { unpaidAmount: feeInfo.value.unpaidAmount, amount: feeInfo.value.amount, lateFee: feeInfo.value.lateFee })
    return '0.00'
  }
  
  // 计算总金额并格式化
  const totalAmount = unpaidAmount + lateFee
  return totalAmount.toFixed(2)
}

// 拨打电话
const handleCall = (phoneNumber) => {
  if (!phoneNumber) return
  
  uni.showModal({
    title: '拨打电话',
    content: `确定要拨打 ${phoneNumber} 吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.makePhoneCall({
          phoneNumber: phoneNumber,
          success: () => {
            console.log('拨打电话成功')
          },
          fail: (error) => {
            console.error('拨打电话失败:', error)
            uni.showToast({
              title: '拨打电话失败',
              icon: 'none'
            })
          }
        })
      }
    }
  })
}

// 图片预览事件处理
const handleImagePreview = (data) => {
  console.log('图片预览事件:', data)
  // AppImagePreview组件会自动处理预览，这里可以添加额外的逻辑
}

// 图片错误事件处理
const handleImageError = (data) => {
  console.error('图片错误事件:', data)
  uni.showToast({
    title: '图片加载失败',
    icon: 'none'
  })
}

// 图片加载事件处理
const handleImageLoad = (data) => {
  console.log('图片加载事件:', data)
}

// 申请延期
const handleReminder = () => {
  if (!feeInfo.value) return
  
  uni.showModal({
    title: '申请延期',
    content: '确定要申请延期缴费吗？延期申请将提交给物业公司审核。',
    success: (res) => {
      if (res.confirm) {
        // 这里应该调用延期申请API
        uni.showToast({
          title: '延期申请已提交',
          icon: 'success'
        })
      }
    }
  })
}

// 联系客服
const handleContact = () => {
  uni.showModal({
    title: '联系客服',
    content: '客服电话：400-123-4567\n工作时间：周一至周日 9:00-18:00',
    showCancel: false,
    confirmText: '确定'
  })
}

// 工具函数：安全格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined || amount === '') return '0.00'
  
  const numAmount = Number(amount)
  if (isNaN(numAmount)) {
    console.warn('金额数据异常:', amount)
    return '0.00'
  }
  
  return numAmount.toFixed(2)
}

// 工具函数：安全获取金额
const getSafeAmount = (amount, defaultValue = 0) => {
  if (amount === null || amount === undefined || amount === '') return defaultValue
  
  const numAmount = Number(amount)
  if (isNaN(numAmount)) {
    console.warn('金额数据异常:', amount)
    return defaultValue
  }
  
  return numAmount
}

// 工具函数
const getStatusText = (status) => {
  const statusMap = {
    'UNPAID': '未支付',
    'PARTIAL': '部分支付',
    'PAID': '已支付',
    'OVERDUE': '已逾期',
    0: '未支付',
    1: '已支付',
    2: '逾期',
    3: '部分支付'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    'UNPAID': 'warning',
    'PARTIAL': 'info',
    'PAID': 'success',
    'OVERDUE': 'error',
    0: 'warning',  // 未支付 - 警告
    1: 'success',  // 已支付 - 成功
    2: 'error',    // 逾期 - 错误
    3: 'info'      // 部分支付 - 信息
  }
  return typeMap[status] || 'info'
}

const getStatusDescription = (status) => {
  const descMap = {
    'UNPAID': '请及时缴费，避免产生滞纳金',
    'PARTIAL': '部分费用已缴纳，请补缴剩余费用',
    'PAID': '费用已全部缴纳完成',
    'OVERDUE': '费用已逾期，请尽快缴费',
    0: '请及时缴费，避免产生滞纳金',
    1: '费用已全部缴纳完成',
    2: '费用已逾期，请尽快缴费',
    3: '部分费用已缴纳，请补缴剩余费用'
  }
  return descMap[status] || '状态描述未知'
}

const getProgressPercentage = () => {
  if (!feeInfo.value || !feeInfo.value.amount) return 0
  
  // 确保数据类型安全，转换为数字类型
  const paidAmount = Number(feeInfo.value.paidAmount) || 0
  const totalAmount = Number(feeInfo.value.amount) || 0
  
  // 验证数字的有效性
  if (isNaN(paidAmount) || isNaN(totalAmount) || totalAmount <= 0) {
    return 0
  }
  
  // 计算百分比并限制在0-100范围内
  const percentage = Math.round((paidAmount / totalAmount) * 100)
  return Math.max(0, Math.min(100, percentage))
}
</script>

<style lang="scss" scoped>
.fee-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 0;
}

.status-section,
.info-section,
.detail-section,
.progress-section,
.records-section,
.payment-section {
  margin: 15px;
}

.status-card,
.info-card,
.detail-card,
.progress-card,
.records-card,
.payment-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  
  .status-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}

.status-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.info-list {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .info-label {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      color: #666;
    }
    
    .info-value {
      font-size: 14px;
      color: #333;
      text-align: right;
      max-width: 60%;
      
      &.due-date {
        color: #ff6b35;
      }
      
      &.amount {
        font-size: 16px;
        font-weight: bold;
        color: #2d8cf0;
      }
    }
  }
}

.detail-list {
  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .detail-label {
      font-size: 14px;
      color: #666;
    }
    
    .detail-value {
      font-size: 14px;
      color: #333;
      font-weight: 500;
      
      &.unpaid {
        color: #ff6b35;
        font-weight: bold;
      }
      
      &.late-fee {
        color: #f56c6c;
        font-weight: bold;
      }
    }
  }
}

.progress-content {
  .progress-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    .progress-text {
      font-size: 14px;
      color: #666;
    }
    
    .progress-amount {
      font-size: 16px;
      font-weight: bold;
      color: #2d8cf0;
    }
  }
  
  .progress-bar {
    height: 8px;
    background: #f0f0f0;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 10px;
    
    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #2d8cf0, #00b4d8);
      border-radius: 4px;
      transition: width 0.3s ease;
    }
  }
  
  .progress-percentage {
    text-align: center;
    font-size: 14px;
    color: #666;
  }
}

.records-list {
  .record-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .record-info {
      .record-time {
        display: block;
        font-size: 14px;
        color: #333;
        margin-bottom: 4px;
      }
      
      .record-method {
        font-size: 12px;
        color: #999;
      }
    }
    
    .record-amount {
      font-size: 16px;
      font-weight: bold;
      color: #2d8cf0;
    }
  }
}

.company-info {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  
  .company-name {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
  }
  
  .company-desc {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }
}

.qr-code-container {
  text-align: center;
  margin-bottom: 20px;
  
  .qr-code-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
    font-weight: 500;
  }
  
  .qr-code-images {
    margin-bottom: 15px;
  }
  
  .qr-code-tip {
    font-size: 12px;
    color: #999;
  }
}

.payment-account-info {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  
  .account-title {
    font-size: 14px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
  }
  
  .account-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .account-label {
      font-size: 14px;
      color: #666;
    }
    
    .account-value {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}

.contact-info {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  
  .contact-title {
    font-size: 14px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
  }
  
  .contact-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .contact-label {
      font-size: 14px;
      color: #666;
    }
    
    .contact-value {
      font-size: 14px;
      color: #007aff;
      font-weight: 500;
      cursor: pointer;
    }
  }
}

.payment-instructions {
  background-color: #f0f8ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  
  .instructions-title {
    font-size: 14px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
  }
  
  .instructions-content {
    .instruction-item {
      display: block;
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      line-height: 1.5;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.action-section {
  margin: 15px;
  padding-bottom: 30px;
  
  .action-buttons {
    display: flex;
    gap: 15px;
    
    .u-button {
      flex: 1;
    }
  }
}

.loading-section,
.error-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  
  .loading-text {
    margin-top: 15px;
    font-size: 14px;
    color: #666;
  }
}
</style>
